<template>
  <div>
      <s-table :search-params="searchParams" :COLUMNS="columns" :async-fc="page" ref="table">
          <template #tableHeader>
              <t-button @click="insert">新增信息</t-button>
              <t-button @click="onDelete" theme="warning">删除</t-button>
          </template>
      </s-table>
      <t-dialog v-model:visible="modalOpen" @confirm="onModalSubmit">
          <t-form ref="submitFormRef" :rules="FORM_RULES" :data="submitForm">
              <t-form-item :label="t('pages.sysRole.name')" name="name">
                  <t-input v-model="submitForm.name" :placeholder="t('pages.sysRole.namePlaceholder')"/>
              </t-form-item>
              <t-form-item :label="t('pages.sysRole.code')" name="code">
                  <t-input v-model="submitForm.code" :placeholder="t('pages.sysRole.codePlaceholder')"/>
              </t-form-item>
              <t-form-item :label="t('pages.sysRole.status')" name="status">
                  <t-radio-group v-model="submitForm.status" :options="statusOptions"/>
              </t-form-item>
              <t-form-item :label="t('pages.sysRole.remarks')" name="remarks">
                  <t-input v-model="submitForm.remarks" :placeholder="t('pages.sysRole.remarksPlaceholder')"/>
              </t-form-item>
          </t-form>
      </t-dialog>
      <t-drawer v-model:visible="drawerOpen" closeBtn :footer="isFooter" size="medium" header="角色权限">
      <t-tree :data="treeData" checkable checkStrictly icon line expandParent lazy expand-all value-mode="all" @change="onChange" :value="checkKeys">
        <template #line="{ node }">
          <t-icon v-if="node.data.icon" :name="node.data.icon" />
          <t-icon v-else name="map-3d" />
        </template>
      </t-tree>
    </t-drawer>
  </div>
</template>
<script setup lang="ts">
/*****                                          引用部分开始                                          *****/
import { onMounted, ref } from "vue";
import { t } from "@/locales";
import STable from "@/components/s-table/index.vue"
import { TableInstanceFunctions } from "@/components/s-table/type";
import { searchParams, COLUMNS, FORM_RULES, statusOptions } from '../sysRole/propos';
import { page, updateApi, insertApi, deleteById, getPermission,roleCheck } from "@/api/sysRole";
import { page as menuApi } from "@/api/sysPermission";
import { FormInstanceFunctions, Link, Space, MessagePlugin, DialogPlugin, TreeProps, Row } from "tdesign-vue-next";
import { getParams } from "tdesign-vue-next/es/utils/render-tnode";
/*****                                          引用部分结束                                          *****/


/*****                                          属性定义部分开始                                          *****/
const submitForm = ref({
  id: null,
  name: '',
  code: '',
  status: '0',
  remarks: '',
});
const modalOpen = ref(false);
const submitFormRef = ref<FormInstanceFunctions>(null);
const table = ref<TableInstanceFunctions>(null);
const drawerOpen = ref(false);
const isFooter = ref(false);
const checkKeys = ref([]);
const roleId = ref('');
const treeData = ref<TreeProps['data']>([]);
/*****                                          属性定义部分结束                                          *****/


const columns = COLUMNS.concat([{
  align: 'left',
  fixed: 'right',
  colKey: 'op',
  title: t('components.commonTable.operation'),
  cell: (h, slot:{row:any}) => h(Space, {}, [
      h(Link, {
          theme: 'primary',
          onClick: () => {
              submitForm.value = slot.row;
              modalOpen.value = true;
          }
      }, '修改'),
      h(Link, {
          theme: 'warning',
          onClick: async() => {
            //打开抽屉前获取拥有的权限
            const data = await getPermission(slot.row.id);
            roleId.value = slot.row.id;
            checkKeys.value = data;
            drawerOpen.value = true;
          }
      }, '权限'),
      h(Link, {
          theme: 'danger',
          onClick: () => {
              const confirmDialog = DialogPlugin.confirm({
                  header: `提示`,
                  body: `删除后，标记为${slot.row.id}的所有信息将被清空，且无法恢复`,
                  confirmBtn: {
                      content: '提交',
                      theme: 'primary',
                      loading: false,
                  },
                  theme: 'warning',
                  onConfirm: async () => {
                      confirmDialog.update({ confirmBtn: { content: '提交中', loading: true } });
                      await deleteById(slot.row.id);
                      MessagePlugin.success('删除成功！');
                      table.value.onSearch();
                      confirmDialog.update({ confirmBtn: { content: '提交', loading: false } });
                      confirmDialog.hide();
                  },
              })
          }
      }, '删除'),
  ])
}]);


/*****                                          页面方法开始                                          *****/
const insert = () => {
  modalOpen.value = true;
  submitForm.value = {
      id: null,
      name: '',
      code: '',
      status: '1',
      remarks: '',
  };
    // 重置表单实例
    if (submitFormRef.value) {
    submitFormRef.value.reset();
  }
}

const onDelete =async () => {
  
}

/**
* 提交表单
*/
const onModalSubmit = async () => {
  const valid = await submitFormRef.value.validate();
  if (valid === true) {
      if (submitForm.value.id) {
          await updateApi(submitForm.value);
          MessagePlugin.success('修改成功！');
      } else {
          await insertApi(submitForm.value);
          MessagePlugin.success('新增成功！');
      }
      // 关闭弹出框
      modalOpen.value = false;
      // 重新加载数据
      table.value.onSearch();
  }
}

const onChange = async(keys:any,e:any) => {
  const data = roleCheck({roleId:roleId.value,check:e.node.check,permissionId:keys});
  if(data){
    checkKeys.value = keys;
    MessagePlugin.success('权限设置成功！');
  }
}

onMounted(async() => {
  // 获取数据
  const {records} = await menuApi({pageNo:1,pageSize:99,params:{type:0,tree:true}});
  treeData.value = records;
  
});

/*****                                          页面方法结束                                          *****/
</script>